import 'dart:typed_data';

import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:hitutor/Util/Global.dart';
import 'package:hitutor/Util/HttpGo.dart';
import 'package:hitutor/Util/MyColor.dart';
import 'package:hitutor/Util/PageUtil.dart';
import 'package:hitutor/Widget/AudioPlayBar.dart';
import 'package:hitutor/Widget/MyButton.dart';
import 'package:hitutor/Widget/MyDialog.dart';
import 'package:hitutor/Widget/MyImage.dart';
import 'package:hitutor/Widget/MyPage.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:photo_view/photo_view.dart';
import 'package:photo_view/photo_view_gallery.dart';

class AudioPlayerPage extends StatefulWidget {
  int lessonId;
  List<dynamic> Files;
  int mode;
  static const int materialMode = 0;
  static const int fileMode = 1;

  AudioPlayerPage({this.mode = materialMode, this.Files = const [], this.lessonId = 0});

  @override
  State<StatefulWidget> createState() {
    return _AudioPlayerPage();
  }
}

class _AudioPlayerPage extends State<AudioPlayerPage> {
  List<dynamic> audioFiles = [];
  List<dynamic> imageFiles = [];
  List<dynamic> videoFiles = [];

  late String type;
  late String url;
  late String name;

  @override
  void initState() {
    if (widget.mode == AudioPlayerPage.materialMode) {
      type = "materialFileType";
      url = "materialFileUrl";
      name = "materialFileName";
    } else {
      type = "fileType";
      url = "url";
      name = "fileName";
    }

    WidgetsBinding.instance?.addPostFrameCallback((timeStamp) {
      if (widget.lessonId != 0)
        getFiles();
      else
        splitFiles();
    });
    super.initState();
  }

  getFiles() {
    HttpGo(context).get("/Material/GetPreviewMaterial?lessonId=${widget.lessonId}", {}, (data) {
      widget.Files = data["materialItems"];
      splitFiles();
    }, (code, error) => showToast(error));
  }

  splitFiles() {
    for (var item in widget.Files) {
      if (item[type].toString().startsWith("audio")) {
        audioFiles.add(item);
      } else if (item[type].toString().startsWith("video")) {
        videoFiles.add(item);
      } else if (item[type].toString().startsWith("image")) {
        imageFiles.add(item);
      }
    }
    setState(() {});
  }

  int selectPos = 0;

  saveImage(String url, String name) async {
    SmartDialog.showLoading();
    var response = await Dio().get(url, options: Options(responseType: ResponseType.bytes));
    final result = await ImageGallerySaver.saveImage(Uint8List.fromList(response.data), quality: 100, name: name);
    print(result);
    SmartDialog.dismiss();
  }

  @override
  Widget build(BuildContext context) {
    String title = imageFiles.length > 0 ? "${selectPos + 1}/${imageFiles.length}" : "";
    return MyPage(
        title,
        Container(
          child: Column(children: [
            Expanded(
                child: PhotoViewGallery.builder(
                    scrollPhysics: const BouncingScrollPhysics(),
                    backgroundDecoration: Global.getWhiteBg(0),
                    builder: (BuildContext context, int index) {
                      return PhotoViewGalleryPageOptions(
                        imageProvider: NetworkImage(imageFiles[index][url]),
                        initialScale: PhotoViewComputedScale.contained,
                        minScale: PhotoViewComputedScale.contained,
                        maxScale: PhotoViewComputedScale.contained * 3,
                        heroAttributes: PhotoViewHeroAttributes(tag: imageFiles[index][url]),
                      );
                    },
                    itemCount: imageFiles.length,
                    loadingBuilder: (context, event) =>
                        Center(child: Container(width: 40.0, height: 40.0, child: CircularProgressIndicator())),
                    onPageChanged: (i) {
                      selectPos = i;
                      setState(() {});
                    })),
            AudioPlayBar(mode: widget.mode, audioFiles: audioFiles, videoFiles: videoFiles)
          ]),
        ));
  }
}

class MenuDialog extends StatelessWidget {
  Function() saveCallback;

  MenuDialog({required this.saveCallback});

  @override
  Widget build(BuildContext context) {
    return Column(mainAxisSize: MainAxisSize.min, children: [
      TextBtn("保存到手機", height: 48, width: double.infinity, style: TextStyle(fontSize: 14), onTap: () {
        saveCallback();
        PageUtil().back(context);
      }),
      Container(height: 0.5, color: MyColor.DD),
      TextBtn("取消", height: 48, width: double.infinity, style: TextStyle(fontSize: 14), onTap: () {
        PageUtil().back(context);
      })
    ]);
  }
}
